package com.example.ios_del1.myapplicationtest;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.widget.ImageView;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ContentHandler;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import jakewharton.disklrucache.DiskLruCache;

/**
 * Created by ios_del1 on 15/9/6.
 */
public class Cache  {
    private Context context;
    private DiskLruCache mDiskLruCache;
    private LruCache<String, Bitmap> lruCache;
    private static final String tag = "ImageCacheUtils";
    private Handler mDelivery;


    private Cache(){
    }

    public Cache(Context context){
        this.context=context;
        initDiskLruCache();
    }
    private void initDiskLruCache() {
        int maxSize = (int) (Runtime.getRuntime().maxMemory()/8);
        lruCache = new LruCache<String, Bitmap>(maxSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes()*value.getHeight();
            }
        };
        mDiskLruCache = null;
        mDelivery = new Handler(Looper.getMainLooper());
        try {
            File cacheDir = getDiskCacheDir(context, "bitmap");
            if (!cacheDir.exists()) {
                cacheDir.mkdirs();
            }
            mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1,
                    1000 * 1024 * 1024);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean getImageBitmap(final ImageView imageView,String key){
        Bitmap bitmap = null;
        //1，内存
        bitmap = lruCache.get(key);
        if(bitmap!=null){
            Log.i(tag, "内存中获取到的图片");
            final Bitmap finalBitmap = bitmap;
            mDelivery.post(new Runnable() {
                @Override
                public void run() {

                    imageView.setImageBitmap(finalBitmap);
                }
            });
            return true;
        }
        return false;

    }

    public void test(final ImageView imageView, String url, int position) {

    }

    public void test(final ImageView imageView,String url) {
        final String key =hashKeyForDisk(url);
        final DiskLruCache.Snapshot snapShot;
        if(getImageBitmap(imageView,key)){
            return;
        }
        try {
            snapShot = mDiskLruCache.get(key);
            if (snapShot == null) {
                Log.e("TAG", "网络下载 ");
                OkHttpClientManager.getDisplayImageDelegate().displayImage(imageView, url, new OkHttpClientManager.ImageDownloaderFinish() {
                    @Override
                    public void setImageDownloaderFinish(InputStream inputStream,Bitmap bitmap) {
                        try {
                            DiskLruCache.Editor editor = mDiskLruCache.edit(key);
                            if (editor != null) {
                                OutputStream outputStream = editor.newOutputStream(0);
                                if (downloadUrlToStream(inputStream, outputStream)) {
                                    editor.commit();
                                } else {
                                    editor.abort();
                                }
                            }
                            mDiskLruCache.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        lruCache.put(key, bitmap);
                    }
                });

            }else{
                Log.e("TAG","本地加载 ");
                InputStream is = snapShot.getInputStream(0);
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                imageView.setImageBitmap(bitmap);
                lruCache.put(key, bitmap);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean downloadUrlToStream(InputStream inputStream, OutputStream outputStream) {
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(outputStream, 8 * 1024);
            int b;
            while ((b = inputStream.read()) != -1) {
                out.write(b);
            }
            return true;
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public String hashKeyForDisk(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }


    private File getDiskCacheDir(Context context, String uniqueName) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return new File(cachePath + File.separator + uniqueName);
    }

    private int getAppVersion(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    public void close() {
        try {
            mDiskLruCache.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void delete(){
        try {
            mDiskLruCache.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public long size(){
      return   mDiskLruCache.size();
    }

    public void remove(String url){
        String key=hashKeyForDisk(url);
        try {
            mDiskLruCache.remove(key);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void flush(){
        try {
            mDiskLruCache.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
